package com.ahstu.learning.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ahstu.learning.R;
import com.ahstu.learning.SubjectActivity.CourseAdapter;
import com.ahstu.learning.SubjectActivity.Subject;
import com.ahstu.learning.base.BaseActivity;
import com.ahstu.learning.bean.CourseMessage;
import com.ahstu.learning.bean.QuestionInfo;
import com.ahstu.learning.learning.Course_list;
import com.ahstu.learning.learning.LearningFragement;
import com.ahstu.learning.leftMenu.AboutActivity;
import com.ahstu.learning.leftMenu.TranslationActivity;
import com.ahstu.learning.model.UserModel;
import com.ahstu.learning.test.TestFragment;
import com.ahstu.learning.turing.MuToActivity;
import com.ahstu.learning.util.ConstantDataChinese;
import com.ahstu.learning.util.ConstantDataEn;
import com.ahstu.learning.util.ConstantDataMath;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.listener.ObseverListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;

public class MainActivity extends BaseActivity implements ObseverListener,View.OnClickListener {

    @Bind(R.id.btn_learning)
    Button btn_learning;
    @Bind(R.id.btn_test)
    Button btn_test;

    //侧滑操作
    @Bind(R.id.btn_logout)
    Button btn_logout;
    @Bind(R.id.tv_left)
    TextView tv_left;

    private RelativeLayout learning_bt_layout,test_bt_layout;

    private LinearLayout leftmenutuling;
    private LinearLayout left_menu_about;
    private LinearLayout translation;
    private long exitTime = 0;

    private List<Fragment> fragment_list;
    private ViewPager learning_vp;
    private View main_line;
    private int line_width;
    private Message message;
    private Handler handle =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    btn_learning.setBackgroundResource(R.drawable.learning_selected);
                    btn_test.setBackgroundResource(R.drawable.bar_test_normal);
                    break;
                case 1:
                    btn_learning.setBackgroundResource(R.drawable.learning_normal);
                    btn_test.setBackgroundResource(R.drawable.bar_test_selected);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initview();
        initData();

        initQuestion();

        //左侧用户名
        SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
        String username = sp.getString("username", "error");
        tv_left.setText(username);

//        //连接服务器
//        final User user = UserModel.getInstance().getCurrentUser();
//        BmobIM.connect(user.getObjectId(), new ConnectListener() {
//            @Override
//            public void done(String uid, BmobException e) {
//                if (e == null) {
//                    // tv_left.setText(user.getUsername());
//                } else {
//                    Logger.e(e.getMessage());
//                }
//            }
//        });
//        //解决leancanary提示InputMethodManager内存泄露的问题


        final DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlaout);
        mDrawerLayout.setDrawerListener(new DrawerListener() {

            @Override
            public void onDrawerClosed(final View arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDrawerOpened(final View arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onDrawerSlide(final View drawerView, final float arg1) {
                final View contentView = mDrawerLayout.getChildAt(0);
                // arg1表示菜单项滑出来的比例，打开菜单时取值为0->1,关闭菜单时取值为1->0
                final float scale = 1 - arg1;
//                final float rightScale = 0.8f + scale * 0.2f;
                final float leftScale = 1 - 0.3f * scale;

                // 左边的动画
                ViewHelper.setScaleX(drawerView, leftScale);
                ViewHelper.setScaleY(drawerView, leftScale);
                ViewHelper.setAlpha(drawerView, 0.6f + 0.4f * (1 - scale));
                ViewHelper.setTranslationX(contentView, drawerView.getMeasuredWidth() * (1 - scale));

                // 右边的动画
                // ViewHelper.setPivotX(contentView, 0);
                // ViewHelper.setPivotY(contentView,
                // contentView.getMeasuredHeight() / 2);
                // contentView.invalidate();
                // ViewHelper.setScaleX(contentView, rightScale);
                // ViewHelper.setScaleY(contentView, rightScale);
            }

            @Override
            public void onDrawerStateChanged(final int arg0) {
                // TODO Auto-generated method stub

            }

        });



    }

    private void initData() {

        translation.setOnClickListener(this);
        leftmenutuling.setOnClickListener(this);
        left_menu_about.setOnClickListener(this);
        //侧滑退出按钮
        btn_logout.setOnClickListener(this);
        learning_bt_layout.setOnClickListener(this);
        test_bt_layout.setOnClickListener(this);

        fragment_list=new ArrayList<>();
        fragment_list.add(new LearningFragement());
        fragment_list.add(new TestFragment());

        //计算view的宽度
        DisplayMetrics dm = new DisplayMetrics();
        //获取到Activity的实际屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        line_width  = dm.widthPixels / fragment_list.size();
        main_line.getLayoutParams().width = line_width;
        main_line.requestLayout();

        //给viewpager设置适配器，初始化
        learning_vp.setAdapter(new FragmentAdapter(getSupportFragmentManager()));
        learning_vp.setCurrentItem(0);
        learning_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                float tagerX = position * line_width + positionOffsetPixels / fragment_list.size();
                ViewPropertyAnimator.animate(main_line).translationX(tagerX)
                        .setDuration(0);
            }

            @Override
            public void onPageSelected(int position) {
                message=new Message();
                if(position==0){
                    message.what=0;
                }else {
                    message.what=1;
                }
                handle.sendMessage(message);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initview() {

        learning_vp= (ViewPager) findViewById(R.id.learning_vp);
        main_line=findViewById(R.id.mainLine);
        translation = (LinearLayout) findViewById(R.id.translation);
        leftmenutuling = (LinearLayout) findViewById(R.id.leftmenutuling1);
        left_menu_about = (LinearLayout) findViewById(R.id.leftmenutuling2);

        learning_bt_layout= (RelativeLayout) findViewById(R.id.learning_bt_layout);
        test_bt_layout= (RelativeLayout) findViewById(R.id.test_bt_layout);
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()){
            case R.id.learning_bt_layout:
                learning_vp.setCurrentItem(0);
                break;
            case R.id.test_bt_layout:
                learning_vp.setCurrentItem(1);
                break;
            case R.id.btn_logout:
                UserModel.getInstance().logout();
                SharedPreferences sp = getSharedPreferences("name", MODE_PRIVATE);
                sp.edit().clear().commit();
                //可断开连接
//                BmobIM.getInstance().disConnect();
                finish();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                break;
            case R.id.translation:
                intent= new Intent(MainActivity.this, TranslationActivity.class);
                startActivity(intent);
                break;
            case R.id.leftmenutuling1:
                intent = new Intent(MainActivity.this, MuToActivity.class);
                startActivity(intent);
                break;
            case R.id.leftmenutuling2:
                intent = new Intent(MainActivity.this, AboutActivity.class);
                startActivity(intent);
                break;

        }

    }


    @Override
    protected void onResume() {
        super.onResume();
//        checkRedPoint();
        //添加观察者-用于是否显示通知消息
//        BmobNotificationManager.getInstance(this).addObserver(this);
        //进入应用后，通知栏应取消
//        BmobNotificationManager.getInstance(this).cancelNotification();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //移除观察者
//        BmobNotificationManager.getInstance(this).removeObserver(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清理导致内存泄露的资源
//        BmobIM.getInstance().clear();
        //完全退出应用时需调用clearObserver来清除观察者
//        BmobNotificationManager.getInstance(this).clearObserver();
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }




    class FragmentAdapter extends FragmentPagerAdapter {

        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragment_list.get(position);
        }

        @Override
        public int getCount() {
            return fragment_list.size();
        }
    }

    //初始话同步题目数据
    public void initQuestion(){
        //获取习题信息
        BmobQuery<QuestionInfo> course_query=new BmobQuery<>();
        course_query.addWhereEqualTo("answerType","chinese");
        course_query.findObjects(MainActivity.this, new FindListener<QuestionInfo>() {
            @Override
            public void onSuccess(List<QuestionInfo> list) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).getAnswerId().toArray(ConstantDataChinese.answerId);
                    list.get(i).getAnswerName().toArray(ConstantDataChinese.answerName);
                    list.get(i).getAnswerOptionA().toArray(ConstantDataChinese.answerOptionA);
                    list.get(i).getAnswerOptionB().toArray(ConstantDataChinese.answerOptionB);
                    list.get(i).getAnswerOptionC().toArray(ConstantDataChinese.answerOptionC);
                    list.get(i).getAnswerOptionD().toArray(ConstantDataChinese.answerOptionD);
                    list.get(i).getAnswerAnalysis().toArray(ConstantDataChinese.answerAnalysis);
                    list.get(i).getAnswerScore().toArray(ConstantDataChinese.answerScore);
                    Toast.makeText(MainActivity.this,"课程更新",Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(int i, String s) {
                Toast.makeText(MainActivity.this,"课程更新失败",Toast.LENGTH_SHORT).show();
            }
        });

        course_query.addWhereEqualTo("answerType","en");
        course_query.findObjects(MainActivity.this, new FindListener<QuestionInfo>() {
            @Override
            public void onSuccess(List<QuestionInfo> list) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).getAnswerId().toArray(ConstantDataEn.answerId);
                    list.get(i).getAnswerName().toArray(ConstantDataEn.answerName);
                    list.get(i).getAnswerOptionA().toArray(ConstantDataEn.answerOptionA);
                    list.get(i).getAnswerOptionB().toArray(ConstantDataEn.answerOptionB);
                    list.get(i).getAnswerOptionC().toArray(ConstantDataEn.answerOptionC);
                    list.get(i).getAnswerOptionD().toArray(ConstantDataEn.answerOptionD);
                    list.get(i).getAnswerAnalysis().toArray(ConstantDataEn.answerAnalysis);
                    list.get(i).getAnswerScore().toArray(ConstantDataEn.answerScore);
                }
            }
            @Override
            public void onError(int i, String s) {
                Toast.makeText(MainActivity.this,"课程更新失败",Toast.LENGTH_SHORT).show();
            }
        });

        course_query.addWhereEqualTo("answerType","math");
        course_query.findObjects(MainActivity.this, new FindListener<QuestionInfo>() {
            @Override
            public void onSuccess(List<QuestionInfo> list) {
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).getAnswerId().toArray(ConstantDataMath.answerId);
                    list.get(i).getAnswerName().toArray(ConstantDataMath.answerName);
                    list.get(i).getAnswerOptionA().toArray(ConstantDataMath.answerOptionA);
                    list.get(i).getAnswerOptionB().toArray(ConstantDataMath.answerOptionB);
                    list.get(i).getAnswerOptionC().toArray(ConstantDataMath.answerOptionC);
                    list.get(i).getAnswerOptionD().toArray(ConstantDataMath.answerOptionD);
                    list.get(i).getAnswerAnalysis().toArray(ConstantDataMath.answerAnalysis);
                    list.get(i).getAnswerScore().toArray(ConstantDataMath.answerScore);
                }
            }
            @Override
            public void onError(int i, String s) {
                Toast.makeText(MainActivity.this,"课程更新失败",Toast.LENGTH_SHORT).show();
            }
        });
    }

}
